import sys
from  PyQt5.QtWidgets import *

class TableDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.initUi()
    def initUi(self):
        self.setWindowTitle("QtableWidget案例")
        self.resize(400,300)
        conLayout=QHBoxLayout()
        tablewidget=QTableWidget()
        tablewidget.setRowCount(4)
        tablewidget.setColumnCount(3)
        conLayout.addWidget(tablewidget)
        tablewidget.setHorizontalHeaderLabels(['姓名','性别','年纪'])
        #tablewidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        tablewidget.setEditTriggers(QAbstractItemView.NoEditTriggers)#禁止编辑
        tablewidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        #行列高度设置与显示相匹配
        tablewidget.resizeColumnsToContents()
        tablewidget.resizeRowsToContents()
        #设置水平方向的表头隐藏
        #tablewidget.verticalHeader().setVisible(False)
        #tablewidget.horizontalHeader().setVisible(False)
        newItem=QTableWidgetItem("张三")

        tablewidget.setItem(0,0,newItem)

        newItem = QTableWidgetItem("男")
        tablewidget.setItem(0, 1, newItem)

        newItem = QTableWidgetItem("20")
        tablewidget.setItem(0, 2, newItem)
        self.setLayout(conLayout)

if __name__ == '__main__':
    app=QApplication(sys.argv)
    table=TableDemo()
    table.show()
    sys.exit(app.exec_())